package org.totoro.amap.service.impl;

import com.googlecode.javaewah.datastructure.BitSet;
import org.totoro.dto.HitTag;
import org.totoro.dto.MultipleTag;
import org.totoro.enums.Strategy;
import org.totoro.amap.service.AbstractBitmap;
import org.totoro.amap.service.BitmapTagService;

import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author daocr
 * @date 2019-04-26
 */

public class LocalBitImpl extends AbstractBitmap implements BitmapTagService {

    private Map<String, BitSet> store = new ConcurrentHashMap<>();

    private ReentrantLock lock = new ReentrantLock();

    @Override
    public HitTag match(@Valid MultipleTag multipleTag, @Valid List<Long> ids) {

        BitSet tag = this.getBitmapByTagName(multipleTag.getTagName());

        if (tag == null) {
            return null;
        }

        AbstractBitmap.BitMapContainer bitMapContainer = new AbstractBitmap.BitMapContainer(ids);

        BitSet calculate = multipleTag.getStrategy().apply(bitMapContainer.getBitSet(), tag);

        return new HitTag(Strategy.conv(calculate));
    }

    @Override
    public HitTag match(@Valid List<MultipleTag> multipleTag, List<Long> ids) {

        BitSet bitSet = super.find(multipleTag, ids);

        return new HitTag(Strategy.conv(bitSet));

    }

    @Override
    public BitSet getBitmapByTagName(String tagName) {
        return store.get(tagName);
    }
}
